package com.cn.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.cn.domain.User;
import com.cn.service.UserService;
import com.cn.service.impl.UserServiceImpl;

/**
 * Servlet implementation class RetrievePassWordServlet
 */
@WebServlet("/RetrievePassWordServlet")
public class RetrievePassWordServlet extends HttpServlet {
	
	private UserService userService=new UserServiceImpl();
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String type=request.getParameter("type");
		System.out.println("type=="+type);
		if("goToUpdateJsp".equals(type)) {
			Map<String,String[]> map=request.getParameterMap();
			User user=new User();
			try {
				BeanUtils.populate(user, map);
				//根据name,id,email进行更新密码：
				user=userService.queryUserByIdAndEmail(user);
				
				if(user!=null) {
					//找到了跳转到修改的界面
					request.setAttribute("userInfo",user);
					//System.out.println("userInfo="+user.getHu_user_name());
					request.getRequestDispatcher("/update_pwd.jsp").forward(request, response);
				}else {
					//没有找到跳转到注册界面
					request.setAttribute("info", "没有找到该用户,请去注册吧!");
					request.getRequestDispatcher("/error.jsp").forward(request, response);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if("getNewPwd".equals(type)) {
			User user=new User();
			try {
				Map<String,String[]> map=request.getParameterMap();
				BeanUtils.populate(user,map);
				//System.out.println("user2Map="+user);
				if(userService.updateNewPwd(user)>0) {
					//修改成功跳转到登陆界面
					request.getRequestDispatcher("/login.jsp").forward(request, response);
				}else {
					//修改失败跳转到重新修改的界面
					request.getRequestDispatcher("/error.jsp").forward(request, response);
				}
			}catch(Exception e) {
				throw new RuntimeException();
			}
		}
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
